<template>
  <div class="session-manager">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索会话..."
        prefix-icon="Search"
        size="small"
      />
    </div>

    <!-- 会话列表 -->
    <div class="session-list" border>
      <div
        v-for="session in filteredSessions"
        :key="session.id"
        class="session-item"
        @dblclick="handleSessionDoubleClick(session)"
      >
        <div class="session-info">
          <span class="session-name">{{ session.Name }}</span>
          <span class="session-time">{{ formatTime(session.CreatedAt) }}</span>
        </div>

        <div class="session-actions">
          <el-button size="small" @click="handleEdit(session)" circle>
            <Edit />
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(session.SessionId)" circle>
            <Delete />
          </el-button>
        </div>
      </div>

      <!-- 空状态 -->
      <el-empty v-if="filteredSessions.length === 0" description="暂无会话记录" />
    </div>

    <!-- 编辑会话名称对话框 -->
    <el-dialog v-model="editDialogVisible" title="修改会话名称" width="300px">
      <el-input
        v-model="editingSessionName"
        placeholder="请输入会话名称"
        @keyup.enter="handleSaveEdit"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveEdit">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="SessionManager">
import { ref, watch, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { Session } from "@/types/types";
import { Delete, Edit } from "@icon-park/vue-next";
import { getSessions, updateSession, deleteSession } from "@/api/flow-api";

// 状态管理
const searchQuery = ref("");
const sessions = ref<Session[]>([]);
const filteredSessions = ref<Session[]>([]);
const editDialogVisible = ref(false);
const currentSessionId = ref<string | null>(null);
const editingSessionName = ref("");

const props = defineProps({
  flowId: {
    type: Number,
    required: true,
  },
});

// 搜索过滤
watch(searchQuery, (val) => {
  filteredSessions.value = sessions.value.filter((session) =>
    session.Name.toLowerCase().includes(val.toLowerCase())
  );
});

// 格式化时间显示
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "long",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
};

// 加载会话列表
const loadSessions = async () => {
  console.log("GetSessions");
  try {
    const res = await getSessions({
      flowId: props.flowId,
    });
    if (res.code === 200 && Array.isArray(res.data)) {
      console.log(res.data);
      sessions.value = res.data;
      filteredSessions.value = [...res.data];
    } else {
      ElMessage.error("加载会话失败");
    }
  } catch (error) {
    ElMessage.error("加载会话失败");
    console.error(error);
  }
};

// 编辑会话
const handleEdit = (session: Session) => {
  currentSessionId.value = session.SessionId;
  editingSessionName.value = session.Name;
  editDialogVisible.value = true;
};

// 保存编辑
const handleSaveEdit = async () => {
  if (!currentSessionId.value || !editingSessionName.value.trim()) {
    ElMessage.warning("会话名称不能为空");
    return;
  }

  try {
    const res = await updateSession({
      id: currentSessionId.value,
      name: editingSessionName.value.trim(),
    });

    console.log("updateSession:", res)
    if (res.code === 200) {
      const index = sessions.value.findIndex((s) => s.SessionId === currentSessionId.value);
      console.log("index", index)
      if (index !== -1) {
        sessions.value[index].Name = editingSessionName.value.trim();
        filteredSessions.value = [...sessions.value];
      }
      ElMessage.success("修改成功");
      editDialogVisible.value = false;
    }
  } catch (error) {
    ElMessage.error("修改失败");
    console.error(error);
  }
};

// 删除会话
const handleDelete = async (id: string) => {
  try {
    await ElMessageBox.confirm("确定要删除这个会话吗？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });


    const res = await deleteSession({id:id});
    if (res.code === 200) {
      sessions.value = sessions.value.filter((session) => session.SessionId !== id);
      filteredSessions.value = [...sessions.value];
      ElMessage.success("删除成功");
    }
  } catch (error) {
    // 用户取消删除或发生错误
    if (error !== "cancel") {
      ElMessage.error("删除失败");
      console.error(error);
    }
  }
};

const emit = defineEmits(['onSessionSelect'])

const handleSessionDoubleClick = (session: Session) => {
  emit('onSessionSelect', session.SessionId);
}

// 初始化加载会话
onMounted(() => {
  loadSessions();
});
</script>

<style scoped>
.session-manager {
  padding: 16px;
  height: 100%;
  box-sizing: border-box;
}

.search-bar {
  margin-bottom: 16px;
}

.session-list {
  height: calc(100% - 56px);
  overflow-y: auto;
}

.session-item {
  display: flex;
  justify-content: space-between;
  align-items: center; /* 垂直居中对齐 */
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
}

.session-info {
  display: flex;
  flex-direction: column; /* 垂直排列子元素 */
  gap: 4px; /* 上下间距 */
}

.session-name {
  font-size: 14px;
  font-weight: 500;
}

.session-time {
  font-size: 12px; /* 缩小字体 */
  color: #606266; /* 可选：添加灰色以区分主次 */
}

.session-actions {
  display: flex;
  gap: 8px;
}
</style>
